package com.david.kafka.auth.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Properties;


/**
 * @author David
 * @desc 获取数据源
 * @date 2022/7/4 10:27
 */
public class DataSourceUtil {

    private static final Logger LOG = LoggerFactory.getLogger(DataSourceUtil.class);

    /**
     * 保证 instance 在所有线程中同步
     */
    private static volatile DruidDataSource dataSource = null;

    public static synchronized DruidDataSource getInstance(Map<String, ?> configs) {
        if (dataSource == null || dataSource.isClosed()) {
            dataSource = initDataSource(configs);
        }

        return dataSource;
    }

    private static final DruidDataSource initDataSource(final Map<String, ?> configs) {
        Properties properties = new Properties();
        for (Map.Entry<String, ?> entry : configs.entrySet()) {
            if (entry.getKey().startsWith("druid.")) {
                String key = entry.getKey();
                String value = (String) entry.getValue();
                LOG.info("datasource connection config: {}:{}", key, value);
                properties.setProperty(key, value);
            }
        }
        dataSource = new DruidDataSource();
        dataSource.configFromPropety(properties);
        return dataSource;
    }
}
